import worker from '@ohos.worker';
import { MyMessage } from '../modele/MyMessage'
import { MessageType } from '../modele/MessageType'
import fileIo from '@ohos.file.fs'

const TAG: string = '[worker]'
// 创建worker线程中与主线程通信的对象
const workerPort = worker.workerPort
let fd: number = 0


// worker线程接收主线程信息
workerPort.onmessage = function (e) {
    // data:主线程发送的消息
    let data = e.data as MyMessage
    console.info(`${TAG} workerPort.onmessage ${e}`)
    let type = data.type
    switch (type) {
        case MessageType.CLOSE: {
            // 关闭线程
            console.info(`${TAG} workerPort.onmessage close`)
            workerPort.close()
            break
        }
        case MessageType.SAVE: {
            console.info(`${TAG} workerPort.onmessage save path: ${data.path}}`)
            if (data.path) {
                // 保存数据到文件
                if (fd <= 0) {
                    fd = fileIo.openSync(data.path, 0o2 | 0o100).fd
                }
                for (var index = 0; index < 1000000; index++) {
                    fileIo.writeSync(fd, 'Worker Thread ' + data.data + '' + index + ' \n')
                }
            }
            // 向主线程发送消息
            workerPort.postMessage(data.data + ' 数据保存完成')
            break
        }
        default: {
            console.error(`${TAG} workerPort.onmessage message type error`)
        }

    }
}

// worker线程发生error的回调
workerPort.onerror = function (e) {
    console.info(`${TAG} workerPort.onerror ${JSON.stringify(e)}`)
}